<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Newsletter extends MY_Controller {

    private $emails = array();
    private $_emailConfig;
    
    public function __construct() {
        parent::__construct();
        $this->load->model('newsletter_mod');
        $this->load->model('users_mod');
        $this->load->library('email');
  
        // define terms for emails
		$this->_emailConfig['mailtype'] = 'html';
        $this->_emailConfig['useragent'] = 'PHP CodeIgniter';
    }

    /**
     *   
     *    
     */
    public function index() {
        $data['menu_page'] = "newsletter"; // Koja je stranica. current menu item
        $data['states'] = $this->newsletter_mod->getStates();
        $data['users'] = NULL;
        $data['users_from'] = $this->users_mod->getNewsletterUsersFromList();
        $data['contents'] = 'newsletter/newsletter_home';
        $this->load->view('main', $data);
    }

    public function filter_submit() {
        try {
            $filter = $this->input->post('filter');
            $data['users'] = $this->newsletter_mod->getAllUsers($filter);
            $num_users = count($data['users']);
            $html = $this->load->view('newsletter/users_list', $data, true);
            $response = array(
                'ind' => 1,
                'msg' => "",
                'num_users' => $num_users,
                'html' => $html
            );
        } catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage(),
                'num_users' => 0,
                'html' => ''
            );
        }
        echo json_encode($response);
    }

    public function selected_submit() {
        try {
            $selected = $this->input->post('newsletter_selected');
            //print_r($selected);
            if( $selected == NULL )
            {
               $response = array(
                    'ind' => 0,
                    'msg' => lang("must_choose_one_user")
                );
               
            }
            else 
            {
              $response = array(
                  'ind' => 1,
                  'msg' => "",
              );
            }
        } catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage(),
            );
        }

        echo json_encode($response);
    }

    public function send_newsletter() {
        try {
            
            $emails = $this->input->post('newsletter_selected');
            $from_id = $this->input->post('from_id');
            $subject = $this->input->post('subject');
            //$message = $this->input->post('message');
            $message = $_POST['message'];
            if( "" != $from_id && NULL != ($email = $this->users_mod->getUserEmail($from_id))  )
              $from = $email;
            else
              $from = $this->config->item('admin_mail_from');
            
            if( "" == $subject || "" == $message )
            {
              $response = array(
                    'ind' => 0,
                    'msg' => lang("must_enter_subject_and_message")
                );
            }else if ($this->_send_newsletter($emails, $from, $subject, $message)) {
                $response = array(
                    'ind' => 1,
                    'msg' => lang("mail_sent")
                );
            } else {
                $response = array(
                    'ind' => 0,
                    'msg' => lang("mail_not_sent")
                );
            }
        } catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage()
            );
        }
        echo json_encode($response);
    }

    private function _send_newsletter($emails, $from, $subject, $message) {

          $emails_to = implode(",", $emails);
                    
          $this->email->clear();
          $this->email->initialize($this->_emailConfig);

          //$this->email->to($from);
          $this->email->to($this->config->item('admin_mail_from'));
          $this->email->bcc($emails_to);
          
          $this->email->from($from);
          $this->email->subject($subject);
          $this->email->message($message);
          
          if (!$this->email->send()) {
              // Generate error (by CI)
              throw new Exception("Email cannot be sent. Try again or contact admin!");
              //echo $this->email->print_debugger();
              return false;
          }          
       
        return true;
    }

}

?>
